package jacob.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import jacob.bo.Article;
import jacob.service.ArticleService;
import jacob.util.EmojiFilter;
import jacob.util.HttpClientUtil;
import jacob.util.KeyUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zjl on 2017/12/30.
 */
@RestController
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    private static Logger logger = LoggerFactory.getLogger(ArticleController.class);

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @GetMapping("/collect")
    public void  collect(String desc){

        int pageSize = getPageSize(desc);
        for(int i = 1;i<=pageSize;i++){
            logger.info(i+"");
            _getPage(i,desc);
        }

    }


    @GetMapping("/outPut")
    public String output(){
        List<Article> allarticle = articleService.getAllarticle();
//[example link](http://example.com/)
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        StringBuilder articleBuilder = new StringBuilder();
        for (Article article : allarticle) {
            Date publictime = article.getPublictime();
            String dateStr = format.format(publictime);
            articleBuilder.append("[").append(article.getTitle()).append(" -- ").append(dateStr).append("]");
            articleBuilder.append("(").append(article.getLink()).append(")");
            articleBuilder.append("\n");
        }
        logger.info(articleBuilder.toString());
        return articleBuilder.toString();
    }

    private int getPageSize(String desc){


        String url = "https://data.newrank.cn/xdnphb/app/data/searchinaccount/search";
        Map<String,Object> param = new HashMap<>();
        param.put("keyword",desc);
        param.put("media",0);
        param.put("order",1);
        param.put("pag",1);
        param.put("position",0);
        param.put("time",0);
        param.put("secret","OSosPi45PT44");
        param.put("nonce", KeyUtil.getKey(desc,1)[0]);
        param.put("xyz",KeyUtil.getKey(desc,1)[1]);

        try {
            JSONObject send = HttpClientUtil.send(url, param, "UTF-8");
            Map value = MapUtils.getMap(send, "value");
            if (value != null) {
                Integer pagNum = MapUtils.getInteger(value, "pagNum");
                return pagNum;
            }
        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }
        return 0;
    }

    private void _getPage(Integer page,String desc){

        if(page==null){
            page = 1;
        }
        if(KeyUtil.getKey(desc,page)==null){
            logger.info("empty config "+page);
            return;
        }
        String url = "https://data.newrank.cn/xdnphb/app/data/searchinaccount/search";
        Map<String,Object> param = new HashMap<>();
        param.put("keyword",desc);
        param.put("media",0);
        param.put("order",1);
        param.put("pag",page);
        param.put("position",0);
        param.put("time",0);
        param.put("secret","OSosPi45PT44");
        param.put("nonce", KeyUtil.getKey(desc,page)[0]);
        param.put("xyz",KeyUtil.getKey(desc,page)[1]);

        try {
            JSONObject send = HttpClientUtil.send(url, param, "UTF-8");
            Map value = MapUtils.getMap(send, "value");
            if(value!=null){
                Integer pagNum = MapUtils.getInteger(send, "pagNum");

                JSONArray datas = (JSONArray)value.get("datas");
                if(CollectionUtils.isNotEmpty(datas)){
                    for (Object data : datas) {
                        JSONObject o = (JSONObject)data;
                        String title = MapUtils.getString(o, "title");
                        String summary = MapUtils.getString(o, "summary");
                        String url1 = MapUtils.getString(o, "url");
                        String content = MapUtils.getString(o, "content");
                        String publicTime = MapUtils.getString(o, "publicTime");
                        Article article = new Article();
                        article.setTitle(title);
                        article.setSummary(summary);
                        article.setLink(url1);
                        article.setContent(EmojiFilter.filterEmoji(content));
                        Date parse = dateFormat.parse(publicTime);
                        article.setPublictime(parse);
                        logger.debug("save "+title);
                        articleService.save(article);

                    }
                }
                logger.info("s");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
